package com.zyf.project.binaryproto.encoder.impl.fixed;

import com.zyf.project.binaryproto.converter.FixedValueConverter;
import com.zyf.project.binaryproto.encoder.impl.FixedArrayFieldEncoder;
import com.zyf.project.binaryproto.specification.BinarySliceSpecification;
import com.zyf.project.binaryproto.specification.FieldSpecification;
import org.jetbrains.annotations.NotNull;
import utils.binary.BytesSlices;
import utils.binary.impl.BytesSlice;
import utils.binary.impl.FixedBytesSliceArray;
import utils.binary.io.BytesOutputBuffer;
import utils.io.NumberMask;

import java.lang.reflect.Method;

/**
 * <h1>静态字节数组编码器</h1>
 * <p>继承了 {@link FixedArrayFieldEncoder}</p>
 *
 * @author Zhou Yifan
 */
public class FixedByteArrayFieldEncoder extends FixedArrayFieldEncoder {

    private static final byte[] EMPTY_ARRAY = {};

    public FixedByteArrayFieldEncoder(
            BinarySliceSpecification binarySliceSpecification,
            FieldSpecification fieldSpecification,
            Method reader,
            FixedValueConverter valueConverter) {
        super(binarySliceSpecification, fieldSpecification, reader, valueConverter);
    }

    /**
     * 对数组类型的值进行固定长度的编码；
     *
     * @param values 待编码数组
     * @param buffer 目标缓存
     * @return 写入的字节数
     */
    protected int encodeArray(Object values, @NotNull BytesOutputBuffer buffer) {
        byte[] valueArray = values == null ? EMPTY_ARRAY : (byte[]) values;
        int count = valueArray.length;
        int counterSize = NumberMask.NORMAL.getMaskLength(count);
        int size = counterSize + count;
        byte[] outBuff = new byte[size];
        NumberMask.NORMAL.writeMask(count, outBuff, 0);
        // 优化：直接复制数组；
        System.arraycopy(valueArray, 0, outBuff, counterSize, count);

        buffer.write(outBuff);
        return size;
    }

    @Override
    public Object decodeField(@NotNull BytesSlices fieldBytes) {
        byte[] values = new byte[fieldBytes.getCount()];
        BytesSlice fieldBytesSlice = ((FixedBytesSliceArray) fieldBytes).getDataSlice(0, values.length);
        fieldBytesSlice.copyTo(values, 0, values.length);
        return values;
    }

}
